<template>
  <div class="gray-page resident-detail-page">
    <nav-bar :title="title"></nav-bar>
    <div class="resident-detail-main page-main">
      <van-sticky class="page-scroll" :offset-top="44">
        <van-form
          validate-trigger="onSubmit"
          :show-error="false"
          ref="from"
          input-align="right"
          error-message-align="right"
          :label-width="138"
          @failed="onFailed"
          @submit="onSubmit"
        >
          <van-collapse v-model="activeNames" :border="false">
            <van-collapse-item size="large" title="房屋信息" name="1">
              <van-field
                required
                readonly
                clickable
                name="placeName"
                v-model="formParams.placeName"
                label="所属场所"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.placeName"
                @input="getBuild"
                @click="houseOpenPopup('place')"
              />
              <van-field
                required
                readonly
                clickable
                name="buildName"
                v-model="formParams.buildName"
                label="楼栋"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.buildName"
                @input="getUnit"
                @click="houseOpenPopup('build')"
              />
              <van-field
                required
                readonly
                clickable
                name="unitName"
                v-model="formParams.unitName"
                label="单元"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.unitName"
                @input="getFloor"
                @click="houseOpenPopup('unit')"
              />
              <van-field
                required
                readonly
                clickable
                name="floorName"
                v-model="formParams.floorName"
                label="楼层"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.floorName"
                @click="houseOpenPopup('floor')"
              />
              <van-field
                required
                readonly
                clickable
                name="houseName"
                v-model="formParams.houseName"
                label="房间号"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.houseName"
                @click="houseOpenPopup('house')"
              />
              <van-field
                required
                readonly
                clickable
                name="houseStateName"
                v-model="formParams.houseStateName"
                label="房屋使用类型"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.houseStateName"
                @click="dictOpenPopup('houseState')"
              />
              <van-field
                v-if="formParams.houseState === '2'"
                required
                readonly
                clickable
                name="expirationData"
                v-model="formParams.expirationData"
                label="租住截止时间"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.expirationData"
                @click="dateOpenPopup('expirationData')"
              />
            </van-collapse-item>
            <van-collapse-item size="large" title="基础信息" name="2">
              <van-field
                required
                name="companyName"
                v-model="formParams.companyName"
                label="单位名称"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="50"
                :rules="rules.companyName"
              />
              <van-field
                required
                readonly
                clickable
                name="companyTypeName"
                v-model="formParams.companyTypeName"
                label="单位类型"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.companyTypeName"
                @click="dictOpenPopup('companyType')"
              />
              <van-field
                name="businessScope"
                v-model="formParams.businessScope"
                label="经营范围"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="200"
              />
              <van-field name="isLicense" label="是否有营业执照">
                <template #input>
                  <van-radio-group v-model="formParams.isLicense" direction="horizontal">
                    <van-radio v-for="(item, key) in dictData.yesno" :key="key" :name="item.code">
                      {{ item.description }}
                    </van-radio>
                  </van-radio-group>
                </template>
              </van-field>
              <van-field
                name="licenseNum"
                v-model="formParams.licenseNum"
                label="营业执照号"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="30"
              />
              <van-field
                name="phone"
                v-model="formParams.phone"
                label="联系电话"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :rules="rules.phone"
              />
              <van-field
                required
                readonly
                clickable
                name="businessStatusName"
                v-model="formParams.businessStatusName"
                label="经营状态"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.businessStatusName"
                @click="dictOpenPopup('businessStatus')"
              />
              <van-field
                required
                readonly
                clickable
                name="keyCompanyName"
                v-model="formParams.keyCompanyName"
                label="重点单位标识"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.keyCompanyName"
                @click="dictOpenPopup('keyCompany')"
              />
              <van-field
                type="digit"
                name="area"
                v-model="formParams.area"
                label="面积"
                right-icon="arrow"
                placeholder="请输入"
                class="van-field__right-icon-white"
                :maxlength="7"
              />
              <van-field
                readonly
                clickable
                name="fireCtrlEquipmentDue"
                v-model="formParams.fireCtrlEquipmentDue"
                label="消防设备到期时间"
                placeholder="请选择"
                right-icon="arrow"
                @click="dateOpenPopup('fireCtrlEquipmentDue')"
              />
              <van-field
                v-if="formParams.companyType === 'd05'"
                required
                readonly
                clickable
                name="locationClassificationName"
                v-model="formParams.locationClassificationName"
                label="九小场所分类"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.locationClassificationName"
                @click="dictOpenPopup('locationClassification')"
              />
            </van-collapse-item>
            <van-collapse-item size="large" title="负责人信息" name="3">
              <van-field
                name="legalPerson"
                v-model="formParams.legalPerson"
                label="法定代表人"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="50"
                :rules="rules.legalPerson"
              />
              <van-field
                readonly
                clickable
                name="legalPersonIdTypeName"
                v-model="formParams.legalPersonIdTypeName"
                label="法定代表人证件类型"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.legalPersonIdTypeName"
                @click="dictOpenPopup('legalPersonIdType')"
              />
              <van-field
                name="legalPersonIdCard"
                v-model="formParams.legalPersonIdCard"
                label="法定代表人证件号"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :rules="formParams.legalPersonIdType === '111' ? rules.legalPersonIdCard : rules.legalPersonPassport"
              />
              <van-field
                name="legalPersonPhone"
                v-model="formParams.legalPersonPhone"
                label="法定代表人联系电话"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :rules="rules.legalPersonPhone"
              />
              <van-field
                name="operator"
                v-model="formParams.operator"
                label="实际经营人"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="50"
                :rules="rules.operator"
              />
              <van-field
                readonly
                clickable
                name="operatorIdTypeName"
                v-model="formParams.operatorIdTypeName"
                label="实际经营人证件类型"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.operatorIdTypeName"
                @click="dictOpenPopup('operatorIdType')"
              />
              <van-field
                name="operatorIdCard"
                v-model="formParams.operatorIdCard"
                label="实际经营人证件号"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :rules="formParams.operatorIdType === '111' ? rules.operatorIdCard : rules.operatorPassport"
              />
              <van-field
                name="operatorPhone"
                v-model="formParams.operatorPhone"
                label="实际经营人联系电话"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :rules="rules.operatorPhone"
              />
              <van-field label="上传照片" readonly required :label-width="300" :border="false" />
              <van-field
                class="van-field__value--upload"
                input-align="left"
                error-message-align="left"
                :rules="rules.fileList"
              >
                <template #input>
                  <van-uploader
                    name="fileList"
                    v-model="fileList"
                    accept="image/*"
                    :preview-image="false"
                    :max-size="maxSize"
                    :before-read="uploadBeforeRead"
                    :after-read="uploadAfterRead"
                  >
                    <div class="van-uploader__input--yellow-small">
                      <van-image
                        v-if="fileList.length"
                        width="82px"
                        height="102px"
                        fit="cover"
                        style="border-radius: 12px"
                        :src="
                          fileList[fileList.length - 1].content || $config.ImageURl + fileList[fileList.length - 1].url
                        "
                      />
                      <template v-else>
                        <div class="upload-image"><van-icon class="iconImg" name="plus" size="16" /></div>
                        <div class="upload-text">不超过1M</div>
                      </template>
                    </div>
                  </van-uploader>
                </template>
              </van-field>
            </van-collapse-item>
          </van-collapse>
          <div style="padding: 16px">
            <template v-if="$route.query.type === 'Update'">
              <van-button block type="info" native-type="submit" :disabled="buttonDisabled">更新</van-button>
            </template>
            <template v-else>
              <van-button block type="info" native-type="submit" :disabled="buttonDisabled">提交</van-button>
            </template>
          </div>
        </van-form>
      </van-sticky>
    </div>
    <!-- 所属场所 -->
    <van-popup v-model="housePopupShow" round position="bottom">
      <van-picker
        show-toolbar
        :default-index="
          houseData[`${houseType}Data`] &&
          houseData[`${houseType}Data`].findIndex(o => o.code === formParams[`${houseType}Code`])
        "
        :columns="houseData[`${houseType}Data`]"
        value-key="title"
        @cancel="housePopupShow = false"
        @confirm="houseOnConfirm"
      />
    </van-popup>
    <!-- 日期 -->
    <van-popup v-model="datePopupShow" round position="bottom" @close="date = new Date()">
      <van-datetime-picker
        v-model="date"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        :formatter="formatter"
        @cancel="datePopupShow = false"
        @confirm="dateOnConfirm"
      />
    </van-popup>
    <!-- 字典项 -->
    <van-popup v-model="dictPopupShow" round position="bottom" @close="dictValue = ''">
      <van-picker
        show-toolbar
        :default-index="dictData[dictType] && dictData[dictType].findIndex(o => o.code === dictValue)"
        :columns="dictData[dictType]"
        value-key="description"
        @cancel="dictPopupShow = false"
        @confirm="dictOnConfirm"
        @change="dictOnChange"
      />
    </van-popup>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import Upload from '@/mixins/upload'
import SelectPopup from '@/mixins/selectPopup'
import General from '@/api/general'
import Resident from '@/api/resident'
import { FormParams } from './libs/company'
import { residentNameReg, idCardCheck, phoneReg, passPortCardReg } from '@/libs/regexp'
export default {
  mixins: [Upload, SelectPopup],
  data() {
    const expirationDataValidator = () => {
      if (new Date(this.formParams.expirationData).getTime() > new Date().getTime()) {
        return true
      } else {
        return false
      }
    }
    const legalPersonIdTypeNameValidator = () => {
      if (!this.formParams.legalPersonIdCard && this.formParams.legalPersonIdType) {
        return true
      } else if (this.formParams.legalPersonIdCard && !this.formParams.legalPersonIdType) {
        return false
      }
    }
    const legalPersonIdCardValidator = () => {
      return this.formParams.legalPersonIdCard && idCardCheck(this.formParams.legalPersonIdCard)
    }
    const legalPersonPassportValidator = () => {
      return this.formParams.legalPersonIdCard && passPortCardReg.test(this.formParams.legalPersonIdCard)
    }
    const operatorIdTypeNameValidator = () => {
      if (!this.formParams.operatorIdCard && this.formParams.operatorIdType) {
        return true
      } else if (this.formParams.operatorIdCard && !this.formParams.operatorIdType) {
        return false
      }
    }
    const operatorIdCardValidator = () => {
      return this.formParams.operatorIdCard && idCardCheck(this.formParams.operatorIdCard)
    }
    const operatorPassportValidator = () => {
      return this.formParams.operatorIdCard && passPortCardReg.test(this.formParams.operatorIdCard)
    }
    const phoneValidator = () => {
      return this.formParams.phone && phoneReg.test(this.formParams.phone)
    }
    const legalPersonPhoneValidator = () => {
      return this.formParams.legalPersonPhone && phoneReg.test(this.formParams.legalPersonPhone)
    }
    const operatorPhoneValidator = () => {
      return this.formParams.operatorPhone && phoneReg.test(this.formParams.operatorPhone)
    }
    return {
      title: '单位基础信息采集',
      activeNames: ['1', '2', '3'],
      folder: 'approve/company',
      maxSize: 1024 * 1024,
      fileList: [],
      dictTypes: 'houseState,companyType,yesno,businessStatus,keyCompany,idType,locationClassification',

      buttonDisabled: false,
      formParams: new FormParams(),
      rules: {
        placeName: [{ required: true, message: '请选择所属场所' }],
        buildName: [{ required: true, message: '请选择楼栋' }],
        unitName: [{ required: true, message: '请选择单元' }],
        floorName: [{ required: true, message: '请选择楼层' }],
        houseName: [{ required: true, message: '请选择房间号' }],
        houseStateName: [{ required: true, message: '请选择房屋使用类型' }],
        expirationData: [
          { required: true, message: '请选择租住截止时间' },
          { validator: expirationDataValidator, message: '租住截至时间不能小于当前时间' }
        ],

        companyName: [
          { required: true, message: '请输入单位名称' },
          { validator: this.checkName, message: '该单位名称已使用' }
        ],
        companyTypeName: [{ required: true, message: '请选择单位类型' }],
        licenseNum: [{ validator: this.checkLicenseNum, message: '该营业执照号已使用' }],
        phone: [{ validator: phoneValidator, message: '请输入正确的手机号' }],
        businessStatusName: [{ required: true, message: '请选择经营状态' }],
        keyCompanyName: [{ required: true, message: '请选择重点单位标识' }],
        locationClassificationName: [{ required: true, message: '请选择九小场所分类' }],

        legalPerson: [{ pattern: residentNameReg, message: '请输入中文、英文和"·"' }],
        legalPersonIdTypeName: [{ validator: legalPersonIdTypeNameValidator, message: '请选择证件类型' }],
        legalPersonIdCard: [{ validator: legalPersonIdCardValidator, message: '请输入正确的证件号' }],
        legalPersonPassport: [{ validator: legalPersonPassportValidator, message: '请输入正确的证件号' }],
        legalPersonPhone: [{ validator: legalPersonPhoneValidator, message: '请输入正确的手机号' }],

        operator: [{ pattern: residentNameReg, message: '请输入中文、英文和"·"' }],
        operatorIdTypeName: [{ validator: operatorIdTypeNameValidator, message: '请选择证件类型' }],
        operatorIdCard: [{ validator: operatorIdCardValidator, message: '请输入正确的证件号' }],
        operatorPassport: [{ validator: operatorPassportValidator, message: '请输入正确的证件号' }],
        operatorPhone: [{ validator: operatorPhoneValidator, message: '请输入正确的手机号' }],

        fileList: [{ required: true, message: '请上传照片' }]
      },

      // 房屋信息
      houseData: {
        placeData: [],
        buildData: [],
        unitData: [],
        floorData: [],
        houseData: []
      },
      houseType: 'place',
      housePopupShow: false,

      companyFlag: this.$route.query.companyCode
    }
  },
  computed: {
    ...mapState({
      user: state => state.userInfo
    })
  },
  watch: {
    'formParams.placeCode'() {
      this.getBuild()
    },
    'formParams.buildCode'() {
      this.getUnit()
    },
    'formParams.unitCode'() {
      this.getFloor()
    },
    'formParams.floorCode'() {
      this.getHouse()
    }
  },
  created() {
    // 场所
    this.getPlace()
    // 字典项
    this.getDict(this.dictTypes)

    // 更新
    if (this.$route.query.companyCode) {
      this.title = '单位基础信息更新'
      this.getDetail()
    }
  },
  methods: {
    // 获取详情
    getDetail() {
      Resident.BaseInfo.companyDetail({
        companyCode: this.$route.query.companyCode
      }).then(res => {
        const { status, data } = res.data
        if (status === 0) {
          this.formParams = { ...data }
          if (this.formParams.companyImage) {
            this.fileList = [
              {
                url: this.formParams.companyImage
              }
            ]
          }
        }
      })
    },
    dictOnChange() {
      if (this.dictType === 'companyType') {
        this.formParams.locationClassification = ''
        this.formParams.locationClassificationName = ''
      }
    },
    // 房屋所属场所
    getPlace() {
      const params = {
        regionCode: this.user.regionCode
      }
      General.Region.getPlace(params).then(res => {
        const { data, status } = res.data
        if (status === 0) {
          this.houseData.placeData = data
        }
      })
    },
    getBuild() {
      if (!this.companyFlag) {
        this.houseData = {
          placeData: this.houseData.placeData,
          buildData: [],
          unitData: [],
          floorData: [],
          houseData: []
        }
        this.formParams.buildCode = ''
        this.formParams.buildName = ''
        this.formParams.unitCode = ''
        this.formParams.unitName = ''
        this.formParams.floorCode = ''
        this.formParams.floorName = ''
        this.formParams.houseCode = ''
        this.formParams.houseName = ''
      }
      const params = {
        placeCode: this.formParams.placeCode
      }
      General.Region.getBuild(params).then(res => {
        const { data, status } = res.data
        if (status === 0) {
          this.houseData.buildData = data
        }
      })
    },
    getUnit() {
      if (!this.companyFlag) {
        this.houseData = {
          placeData: this.houseData.placeData,
          buildData: this.houseData.buildData,
          unitData: [],
          floorData: [],
          houseData: []
        }
        this.formParams.unitCode = ''
        this.formParams.unitName = ''
        this.formParams.floorCode = ''
        this.formParams.floorName = ''
        this.formParams.houseCode = ''
        this.formParams.houseName = ''
      }
      const params = {
        buildCode: this.formParams.buildCode
      }
      General.Region.getUnit(params).then(res => {
        const { data, status } = res.data
        if (status === 0) {
          this.houseData.unitData = data
        }
      })
    },
    getFloor() {
      if (!this.companyFlag) {
        this.houseData.floorData = []
        this.houseData.houseData = []
        this.formParams.floorCode = ''
        this.formParams.floorName = ''
        this.formParams.houseCode = ''
        this.formParams.houseName = ''
      }
      const params = {
        buildCode: this.formParams.buildCode,
        unit: this.formParams.unitCode
      }
      General.Region.getFloor(params).then(res => {
        const { data, status } = res.data
        if (status === 0) {
          this.houseData.floorData = data
        }
      })
    },
    getHouse() {
      if (!this.companyFlag) {
        this.houseData.houseData = []
        this.formParams.houseCode = ''
        this.formParams.houseName = ''
      }
      const params = {
        buildCode: this.formParams.buildCode,
        unit: this.formParams.unitCode,
        floor: this.formParams.floorCode
      }
      General.Region.getHouse(params).then(res => {
        const { data, status } = res.data
        if (status === 0) {
          this.houseData.houseData = data
        }
      })
    },
    houseOpenPopup(houseType) {
      if (!this.houseData[`${houseType}Data`].length) {
        this.$toast('暂无数据')
        return false
      }
      this.houseType = houseType
      this.housePopupShow = true
    },
    houseOnConfirm(item) {
      this.formParams[`${this.houseType}Code`] = item.code
      this.formParams[`${this.houseType}Name`] = item.title
      this.housePopupShow = false
    },
    // 单位名称判重
    checkName() {
      return new Promise((resolve, reject) => {
        Resident.Init.companyCheck({
          companyCode: this.$route.query.companyCode,
          regionCode: this.user.regionCode,
          companyName: this.formParams.companyName
        }).then(res => {
          resolve(res.data.status === 0)
        })
      })
    },
    // 营业执照号判重
    checkLicenseNum() {
      return new Promise((resolve, reject) => {
        Resident.Init.companyCheck({
          companyCode: this.$route.query.companyCode,
          regionCode: this.user.regionCode,
          licenseNum: this.formParams.licenseNum
        }).then(res => {
          resolve(res.data.status === 0)
        })
      })
    },
    // 表单 - 校验
    onFailed(errorInfo) {
      this.$refs.from.scrollToField(errorInfo.errors[0].name)
    },
    // 表单 - 提交
    onSubmit() {
      this.formParams.companyImage = this.fileList[this.fileList.length - 1].url
      this.buttonDisabled = true
      Resident.BaseInfo[`company${this.$route.query.type || 'Save'}`](this.formParams)
        .then(res => {
          const { status } = res.data
          if (status === 0) {
            this.$router.push({
              path: '/page/message',
              query: {
                backTo: this.$route.query.type ? '-2' : '-1',
                title: this.$route.query.type ? '更新成功' : '提交成功'
              }
            })
          } else {
            this.$toast.fail(res.data.message)
          }
          this.buttonDisabled = false
        })
        .catch(() => {
          this.buttonDisabled = false
        })
    }
  }
}
</script>
<style lang="less" scoped>
@import '~@/assets/style/resident/detail.less';
</style>
